package com.atguigu.juc;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantReadWriteLock;

class MyCache {
    HashMap<String, String> hashMap = new HashMap<>();

    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();
    public void write(String key,String value) {
            rwl.writeLock().lock();
            try
            {
                System.out.println(Thread.currentThread().getName()+"\t"+"开始写");
                String result = hashMap.put(key, value);
                try { TimeUnit.MILLISECONDS.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); }
                System.out.println(Thread.currentThread().getName()+"\t"+"写了"+result);
            }finally {
                rwl.writeLock().unlock();
            }
    }
    public void read(String key){
        rwl.readLock().lock();
        try
        {
            System.out.println(Thread.currentThread().getName()+"\t"+"开始读");
            String s = hashMap.get(key);
            System.out.println(Thread.currentThread().getName()+"\t"+key);
        }finally {
            rwl.readLock().unlock();
        }
    }

}

public class ReadWriteLockDemo {

    public static void main(String[] args) {
        MyCache myCache = new MyCache();

        for (int i = 1; i <=10; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.write(finalI +"", finalI +"");
            },String.valueOf(i)).start();
        }

        //暂停毫秒
        try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); }

        for (int i = 1; i <=10; i++) {
            int finalI = i;
            new Thread(() -> {
                myCache.read(finalI +"");
            },String.valueOf(i)).start();
        }
    }
}
